'use strict';

const Service = require('egg').Service;
const { Op } = require("sequelize");

class ThemeService extends Service {

    async findById(id, userId) {
        const theme = await this.ctx.model.Theme.findByPk(id, {
            include: [
                {
                    model: this.ctx.model.ThemeImage,
                    as: 'images'
                },
                {
                    model: this.ctx.model.User,
                    as: 'user'
                },
                {
                    model: this.ctx.model.Category,
                    as: 'category'
                },
                {
                    model: this.ctx.model.ThemeLike,
                    as: 'like'
                },
                {
                    model: this.ctx.model.ThemeComment,
                    as: 'comment',
                    order: [
                        ['create_time', 'DESC']
                    ]
                },
                
            ],
        });
        if (theme) {
            theme.dataValues.likeCount = theme.dataValues.like.length;
            theme.dataValues.commentCount = theme.dataValues.comment.length;
            const like = await this.service.themeLike.findByThemeIdUserId(id, userId);
            if (like) {
                theme.dataValues.isLike = true;
            } else {
                theme.dataValues.isLike = false
            }
            const reading = theme.dataValues.reading + 1;
            //增加阅读量
            theme.update({
                reading
            })
        }
        
        return theme;
    }

    /**
     * 广场话题
     */
    async squareTheme(userId, type, sex, page = 0, size = 15) {
        let where = {
            online: true
        }
        //推荐
        if (type == 'recommend') {
            where.recommend = true;
        }
        //匿名
        if (type == 'anonymity') {
            where.anonymity = true;
        }
        //全部，男，女
        if (sex > 0) {
            const userIds = await this.service.user.findBySex(sex);
            where.user_id = {
                [Op.in]: userIds
            }
        }

        const { rows, count } = await this.ctx.model.Theme.findAndCountAll({
            include: [
                {
                    model: this.ctx.model.ThemeImage,
                    as: 'images'
                },
                {
                    model: this.ctx.model.User,
                    as: 'user'
                },
                {
                    model: this.ctx.model.Category,
                    as: 'category'
                },
                {
                    model: this.ctx.model.ThemeLike,
                    as: 'like'
                },
                {
                    model: this.ctx.model.ThemeComment,
                    as: 'comment',
                    order: [
                        ['create_time', 'DESC']
                    ],
                    include: [
                        {
                            model: this.ctx.model.User,
                            as: 'user',
                            attributes: ['id', 'nickname']
                        }
                    ]
                },
                
            ],
            where: where,
            order: [
                ['create_time', "DESC"]
            ],
            offset: page * size,
            limit: size,
        })
        rows.forEach(r => {
            r.dataValues.likeCount = r.dataValues.like.length;
            r.dataValues.commentCount = r.dataValues.comment.length;
            r.dataValues.isLike = this.isLike(r.dataValues.like, userId);
        })
        return { item: rows, totalCount: count};
    }

    isLike(like, userId) {
        let isLike = false;
        if (like) {
            like.forEach(l => {
                if (l.dataValues.user_id == userId) {
                    
                    isLike = true;
                }
            })
        } 
        return isLike;
    }

    async findByUserId(userId, categoryId, page = 0, size = 15) {
        let where = {
            user_id: userId,
            online: true
        };
        if (categoryId > 0) {
            where.category_id = categoryId
        }
        const { rows, count } =  await this.app.model.Theme.findAndCountAll({
            where: where,
            include: [{
                    model: this.app.model.ThemeImage,
                    as: 'images',
                    attributes: ['id', 'image', 'theme_id']
                },
                {
                    model: this.app.model.Category,
                    as: 'category',
                    attributes: ['id', 'name', 'title']
                }
            ],
            order: [
                ['create_time', 'desc']
            ],
            offset: page * size,
            limit: size
        })
        return { item: rows, totalCount: count}
    }

    // 新增话题
    async addTheme(params) {
        const { ctx } = this;
        let themeData = {};
        let imageData = {};
        const title = params.category_title;
        
        delete params.category_title;
        for (let key in params) {
            if (key.indexOf('theme') >= 0) { // theme 前缀加上theme 来区分，入库时去掉
                imageData[key.slice(5)] = params[key];
            } else {
                themeData[key] = params[key];
            }
        }

        // 使用事物
        return ctx.model.transaction(async t => {
            try {
                const theme = await ctx.model.Theme.create(themeData, {
                    transaction: t
                });
                console.log(imageData)
                if (imageData && "image" in imageData) {
                    console.log(1234);
                    const theme_id = theme.dataValues.id;
                    const image = await ctx.model.ThemeImage.create({...imageData, theme_id}, {
                        transaction: t
                    });
                    return {
                        theme,
                        image
                    };
                }
                return {
                    theme
                };
            } catch (err) {
                console.log(err);
                ctx.helper.commonErr('添加帖子失败！', {});
            }
        });
    }
}

module.exports = ThemeService;